//
//  dataModel.swift
//  Accounting
//
//  Created by Qingke on 16/5/10.
//  Copyright © 2016年 Qingke. All rights reserved.
//

import UIKit

class DataModel: NSObject {

    var iconCategory: [IconCategory]
    
    
    override init() {
        //初始化自己的变量
        iconCategory = [IconCategory]()
        //调用super.init
        super.init()
        //调用函数其它方法
        loadData()

    }
//创建文件存储路径
    func dataFilePath() ->String {
        let path = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)
        let filePath = path[0] as NSString
        
        return filePath.stringByAppendingPathComponent("Acounting-iconCategory.plist")
    }
//保存文件
    func saveData() {
        //创建data对象
        let data = NSMutableData()
        //把数据写入到data对象中来
        let archiver = NSKeyedArchiver(forWritingWithMutableData: data)
        archiver.encodeObject(iconCategory, forKey: "iconCategoryKey")
        archiver.finishEncoding()
        //把data内容写入到文件中
        data.writeToFile(dataFilePath(), atomically: true)
        
    }
//下载文件
    func loadData() {
        //创建data对象
        let data = NSData(contentsOfFile: dataFilePath())
        //把文件内容读出到data中
        if let data = data {
            let unarchiver = NSKeyedUnarchiver(forReadingWithData: data)
            unarchiver.decodeObjectForKey("iconCategoryKey") as! [IconCategory]
            unarchiver.finishDecoding()
        }
        
    }
}
